package org.spring.websocket;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;


public class MessageHandler extends TextWebSocketHandler {
	private static final Log log= LogFactory.getLog(MessageHandler.class);
	
	private Map<String,WebSocketSession> users = new HashMap<String,WebSocketSession>();
	
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		if(!"".equals(message.getPayload()))
			session.sendMessage(message);
		
	}
	
	public void afterConnectionEstablished(WebSocketSession session)throws Exception {
		log.info("Connection established");
		users.put(session.getId(), session);
		String username = (String) session.getAttributes().get("username");
		if(users != null){
			for(WebSocketSession wssession : users.values()){
				handleMessage(wssession, new TextMessage(username + " joined!!"));
			}
		}
	}
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		log.info("Connection closed. Status: " + status);
		users.remove(session.getId());
		String username = (String) session.getAttributes().get("username");
		if(users != null){
			for(WebSocketSession wssession : users.values()){
				handleMessage(wssession, new TextMessage(username + " left!!"));
			}
		}
	}
	
	public void sendMsgToUsers(TextMessage message) throws Exception{
		if(users != null){
			for(WebSocketSession wssession : users.values()){
				handleMessage(wssession, message);
			}
		}
	}
	
	
}